<?php

require_once 'core.php';
require_once cf\Config::path.'shop.php';

$tpl = 'import_csv';

$step = 1;
$smarty->assignByRef('step', $step);

function do_edit_save($aid, $params) {
	global $step, $smarty, $view;
	
	if (array_key_exists('fields',$params)) { //step 2 submitted
		$addAction = cf\api\admin\getAction($view['add_action']['id']);
		$q = \cf\createQuery($addAction['query']);
		if (($f = fopen($params['csv'],'r')) !== false) {
			$first = true;
			while (($values = fgetcsv($f,0,$params['fields_delimiter'])) !== false) {
				if ($first) {
					$first = false;
					if ($params['has_names']) {
						continue;
					}
				}
				$p = array();
				foreach ($params['fields'] as $nm => $pos) {
					$q->setParam($nm, ($pos!='') ? $values[$pos] : null);
				}
				$q->execute();
			}
			fclose($f);
			unlink($params['csv']);
		} else {
			die('error');
		}
	} else if (array_key_exists('csv',$_FILES)) { //step 1 submitted
		if (UPLOAD_ERR_OK != $_FILES['csv']['error'] || !is_uploaded_file($_FILES['csv']['tmp_name'])) {
			//if a file is not uploaded check upload_max_filesize or post_max_size in php.ini
			die('error');
		}
		
		$path = cf\Config::path.'../upload/'.uniqid('csv');
		
		if (move_uploaded_file($_FILES['csv']['tmp_name'], $path)) {
			chmod($path, 0644);
		} else {
			die('error');
		}
		
		if (($f = fopen($path,'r')) !== false) {
			$fdelim = ($params['fields_delimiter']!='other') ? $params['fields_delimiter'] : $params['other_fields_delimiter'];
			$smarty->assign('csv_fields',json_encode(fgetcsv($f, 0, $fdelim)));
			fclose($f);	
			
			$smarty->assign('csv', str_replace('\\', '/', $path));
			$smarty->assign('has_names',$params['has_names']);
			$smarty->assign('fields_delimiter', $fdelim);
			
			$addAction = cf\api\admin\getAction($view['add_action']['id']);
			$smarty->assign('editParams', json_encode($addAction['params']));
			
			$step = 2;
		} else {
			die('error');
		}
	}
}

require_once 'edit.php';
?>